#pragma once
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <unistd.h>

#define NUM 3

typedef void (*task_t)(); // 函数指针类型

// 下载
void DownLoad()
{
    std::cout << "i am DownLoad task" << std::endl;
}

// 输出
void Print()
{
    std::cout << "i am Print task" << std::endl;
}

// 刷新
void Flush()
{
    std::cout << "i am Flush task" << std::endl;
}

task_t tasks[NUM]; // 创建任务的指针指针数组
// 加载任务
void LoadTask()
{
    srand(time(nullptr) ^ 177777777);
    tasks[0] = Print;
    tasks[1] = DownLoad;
    tasks[2] = Flush;
}

// 执行任务
void ExcuteTask(int num)
{
    if (num > 2 || num < 0)
        return;
    tasks[num]();
}

int SelectTask()
{
    return rand() % NUM;
}

// 子进程执行的任务
void work()
{
    while (true)
    {
        int command = 0;
        int n = read(0, &command, sizeof command);
        if (n == sizeof(command))
        {

            std::cout << "pid is: " << getpid() << "task: " << std::endl;
            ExcuteTask(command);
            std::cout << "hehe" << std::endl;
        }
        else if (n == 0)
        {
            std::cout << "sub process :" << getpid() << " is quit...." << std::endl;
            break;
        }
        else
        {
            std::cerr << "error" << std::endl;
            break;
        }
    }
}
